package com.ck.ips.service.impl.sys;

import com.ck.common.model.OperationResult;
import com.ck.common.model.Role;
import com.ck.common.page.PageInfo;
import com.ck.core.constant.BusinessConstant;
import com.ck.core.constant.PageConstant;
import com.ck.core.constant.SymbolConstant;
import com.ck.core.context.UserContextHolder;
import com.ck.ips.dao.RoleDeviceGroupMapper;
import com.ck.ips.dao.sys.RoleMapper;
import com.ck.ips.model.vo.sys.RoleListVO;
import com.ck.ips.model.vo.sys.RoleSelectListVO;
import com.ck.ips.service.sys.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色实现类
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RoleDeviceGroupMapper roleDeviceGroupMapper;
	/** 角色名最大长度 */
	private final int MAX_ROLE_NAME_LENGTH = 16;
	/**
	 * 插入角色
	 *  @param role      Role
	 * @param moduleIds 模块IDS
	 * @param deviceGroupIds
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult insertRole(Role role, String moduleIds, String deviceGroupIds){
		String roleName = role.getRoleName();
		if (StringUtils.isBlank(roleName)) {
			return OperationResult.newValidateFailOperationResult("角色名称不能为空");
		}
		if ( roleName.length() > MAX_ROLE_NAME_LENGTH) {
			return OperationResult.newValidateFailOperationResult("角色名称不能超过"+ MAX_ROLE_NAME_LENGTH +"位");
		}
		if ( role.getStatus() == null ) {
			return OperationResult.newValidateFailOperationResult("请选择是否启用该角色");
		}
		//验证角色是否存在
		Role oldRole = this.getRoleByRoleName(roleName);
		if (oldRole != null) {
			return OperationResult.newValidateFailOperationResult("角色名称已存在，请重新输入角色名称");
		}

		role.setAddTime(System.currentTimeMillis());
		role.setOperator(UserContextHolder.currentUser().getUserName());
		//保存角色
		roleMapper.insertRole(role);
		Long roleId = role.getRoleId();
		if ( roleId != null && StringUtils.isNotBlank(moduleIds)) {
			//保存角色模块关系
			insertRoleModule(roleId, moduleIds);
		}
		if ( roleId != null && StringUtils.isNotBlank(deviceGroupIds)) {
			//保存角色终端分组关系
			roleDeviceGroupMapper.insert(roleId, deviceGroupIds.split(SymbolConstant.COMMA_EN));
		}

		return OperationResult.newSuccessTipsOperationResult("新增角色：" + roleName);
	}

	/**
	 * 修改角色
	 *  @param role      Role
	 * @param moduleIds 模块IDS
	 * @param deviceGroupIds
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult updateRole(Role role, String moduleIds, String deviceGroupIds){
		if ( role == null || role.getRoleId() == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要修改的角色");
		}
		if ( BusinessConstant.INSTALLER_ROLE_ID.equals(role.getRoleId()) ) {
			return OperationResult.newValidateFailOperationResult("不能修改安装员角色");
		}
		String roleName = role.getRoleName();
		if ( StringUtils.isBlank(roleName) ) {
			return OperationResult.newValidateFailOperationResult("请填写角色名称");
		}
		if ( roleName.length() > MAX_ROLE_NAME_LENGTH) {
			return OperationResult.newValidateFailOperationResult("角色名称不能超过"+ MAX_ROLE_NAME_LENGTH +"位");
		}
		if ( role.getStatus() == null ) {
			return OperationResult.newValidateFailOperationResult("请选择是否启用该角色");
		}
		Role oldRole = roleMapper.getRoleById(role.getRoleId());
		if ( oldRole == null ) {
			return OperationResult.newValidateFailOperationResult("未找到需要修改的角色");
		}

		//验证角色名称是否存在
		Role existedRoleId = this.getRoleByRoleName(roleName);
		if ( existedRoleId != null && !existedRoleId.getRoleId().equals(role.getRoleId()) ) {
			return OperationResult.newValidateFailOperationResult("角色名称已存在，请重新输入角色名称");
		}
		//修改角色
		role.setUpdateTime(System.currentTimeMillis());
		role.setOperator(UserContextHolder.currentUser().getUserName());
		roleMapper.updateRoleById(role);
		Long roleId = role.getRoleId();
		if ( moduleIds != null) {
			//删除角色模块关系
			roleMapper.deleteRoleModuleByRoleId(roleId);

			//重新添加角色模块关系
			insertRoleModule(roleId, moduleIds);
		}
		if ( deviceGroupIds != null ) {

			//删除角色分组关系
			roleDeviceGroupMapper.delByRoleId(roleId);

			//保存角色终端分组关系
			if ( StringUtils.isNotBlank(deviceGroupIds) ) {
				roleDeviceGroupMapper.insert(roleId, deviceGroupIds.split(SymbolConstant.COMMA_EN));
			}
		}
		return  OperationResult.newSuccessTipsOperationResult("修改角色信息:" + oldRole.getRoleName());
	}

	/**
	 * 保存角色模块关系
	 *
	 * @param roleId    角色ID
	 * @param moduleIds 模块IDS
	 */
	@Transactional( rollbackFor = Exception.class)
	public void insertRoleModule(Long roleId, String moduleIds) {
		if ( BusinessConstant.INSTALLER_ROLE_ID.equals(roleId) ) {
			return;
		}
		if (roleId != null && StringUtils.isNotBlank(moduleIds)) {
			roleMapper.insertRoleModule(roleId, moduleIds.split(SymbolConstant.COMMA_EN));
		}
	}

	/**
	 * 根据角色名称获取角色
	 *
	 * @param roleName    角色名称
	 * @return Role(角色)
	 */
	@Override
	public Role getRoleByRoleName( String roleName ) {
		return roleMapper.getRoleByRoleName(roleName, BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取角色列表
	 *
	 * @param status      状态
	 * @param roleName    角色名称
	 * @param pageNum     当前页
	 * @param pageSize    条数
	 * @return PageInfo<RoleListVO>
	 */
	@Override
	public PageInfo<RoleListVO> listRole(Integer status, String roleName, Integer pageNum, Integer pageSize){
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<RoleListVO> page = roleMapper.listRole(status, roleName);

		List<RoleListVO> result = page.getResult();
		if(CollectionUtils.isNotEmpty(result)){
			List<Role> roleList = roleMapper.listRoleByUserId(UserContextHolder.currentUser().getUserId());
			if(CollectionUtils.isNotEmpty(roleList)){
				List<Long> roleIdList = roleList.parallelStream().map(Role::getRoleId).collect(Collectors.toList());
				for (RoleListVO roleListVO : result) {
					if(roleIdList.contains(roleListVO.getRoleId())){
						roleListVO.setLoginUserRole(true);
					}
				}
			}
		}

		//把Page转化为PageInfo
		return PageInfo.convert(page);
	}

	/**
	 * 获取所有启用的角色
	 *
	 * @return List<RoleSelectListVO>
	 */
	@Override
	public List<RoleSelectListVO> listRoleSelect() {
		return roleMapper.listRoleSelect(BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取角色拥有的权限名称
	 *
	 * @param roleId 角色ID
	 * @return List<String>
	 */
	@Override
	public List<String> listModuleNamesByRoleId(Long roleId) {
		if (roleId != null) {
			return roleMapper.listModuleNamesByRoleId(roleId);
		}
		return null;
	}

	/**
	 * 根据角色Id获取拥有的权限Id
	 *
	 * @param roleId
	 * @return
	 */
	@Override
	public List<String> listModuleIdsByRoleId(Long roleId) {
		if (roleId != null) {
			return roleMapper.listModuleIdsByRoleId(roleId);
		}
		return null;
	}

	/**
	 * 禁用启用角色
	 *
	 * @param roleId      待操作的角色
	 * @param status      状态
	 * @author linqiang
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult enableDisableRole(Long roleId,Integer status) {
		if ( roleId == null || status == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要操作的角色");
		}
		if ( BusinessConstant.INSTALLER_ROLE_ID.equals(roleId) ) {
			return OperationResult.newValidateFailOperationResult("不能操作安装员角色");
		}
		Role oldRole = roleMapper.getRoleById(roleId);
		if ( oldRole == null ) {
			return OperationResult.newValidateFailOperationResult("未找到相关角色信息");
		}
		oldRole.setUpdateTime(System.currentTimeMillis());
		oldRole.setStatus(status);
		roleMapper.updateRoleById(oldRole);
		return OperationResult.newSuccessTipsOperationResult("启用/禁用角色：" + oldRole.getRoleName());
	}

	/**
	 * 判断用户的所有角色是否被禁用
	 * @param userId
	 * @return
	 */
	@Override
	public boolean isAllDisableByUser(Long userId) {
		List<Role> roleList = roleMapper.listRoleByUserId(userId);
		if(CollectionUtils.isEmpty(roleList)){
			return true;
		}
		boolean isAllDisable = true;
		for (Role role : roleList) {
			if (role.getStatus() == BusinessConstant.STATUS_ENABLE) {
				isAllDisable = false;
			}
		}
		return isAllDisable;
	}

	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult deleteRole(Long roleId) {
		if ( roleId == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要删除的角色");
		}
		if ( BusinessConstant.INSTALLER_ROLE_ID.equals(roleId) ) {
			return OperationResult.newValidateFailOperationResult("不能操作安装员角色");
		}
		Role oldRole = roleMapper.getRoleById(roleId);
		if ( oldRole == null ) {
			return OperationResult.newValidateFailOperationResult("要操作的角色数据不存在");
		}

		List<Long> userIdByRoleId = roleMapper.getUserIdByRoleId(roleId);
		if ( userIdByRoleId != null && !userIdByRoleId.isEmpty() ) {
			return OperationResult.newValidateFailOperationResult("角色已有用户关联，请先解除关联关系");
		}



		// 删除角色与终端组的关联关系
		roleDeviceGroupMapper.delByRoleId(roleId);

		// 删除角色与菜单资源的关联关系
		roleMapper.deleteRoleModuleByRoleId(roleId);

		// 删除角色
		roleMapper.deleteRoleByRoleId(roleId);
		return OperationResult.newSuccessTipsOperationResult("删除角色：" + oldRole.getRoleName());
	}
}
